package com.xunchi.haichuan.utility;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.codehaus.plexus.util.Base64;

/**
 * 作者：kongxb<br>
 * 模块名称：工具模块<br>
 * 功能描述：杂项处理工具<br>
 * 维护记录：2009.11.27, kongxb 创建该类
 */
public class MiscUtil {

	/**
	 * 获取当前系统日期时间。
	 * 
	 * @return
	 */
	public static Date getCurrentDate() {
		return Calendar.getInstance().getTime();
	}

	/**
	 * 以当前系统时间产生随机名字，用于文件和文件夹。
	 * 
	 * @return
	 */
	public static String getRandomName() {
		Random random = new Random(System.currentTimeMillis());
		int rdm = random.nextInt(100);
		Timestamp now = new Timestamp((new java.util.Date()).getTime());
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String name = fmt.format(now).toString().trim() + StringUtils.leftPad(String.valueOf(rdm), 3, '0');
		return name;
	}

	/**
	 * 产生UUID。
	 * 
	 * @return
	 */
	public static String generateUUID() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replaceAll("-", "");
	}

	/**
	 * Try a series of file names.
	 * <p>
	 * The rule is based on: (e.g. "filename.ext")
	 * <li>"filename.ext" not exists, return it;</li>
	 * <li>"filename.ext" exists, return "filename(1).ext";</li>
	 * <li>"filename(1).ext" exists, return "filename(2).ext";</li>
	 * <li>...</li>
	 * </p>
	 * 
	 * @param file
	 * @return
	 */
	public static File getNotExistsFile(String file) {
		return getNotExistsFile(new File(file));
	}

	/**
	 * Try a series of file names.
	 * <p>
	 * The rule is based on: (e.g. "filename.ext")
	 * <li>"filename.ext" not exists, return it;</li>
	 * <li>"filename.ext" exists, return "filename(1).ext";</li>
	 * <li>"filename(1).ext" exists, return "filename(2).ext";</li>
	 * <li>...</li>
	 * </p>
	 * 
	 * @param file
	 * @return
	 */
	public static File getNotExistsFile(File file) {
		if (file == null || !file.exists()) {
			return file;
		}

		String fileName = null;
		String parent = file.getParent();
		if (parent == null) {
			parent = "/";
		}
		parent = parent.concat(File.separator);
		String full = file.getName();
		// main
		String name = "";
		// extended
		String ext = "";
		int r = full.lastIndexOf('.');
		if (r != -1) { // has ext
			name = full.substring(0, r);
			ext = full.substring(r);
		} else { // no ext
			name = full;
		}
		int end = name.length() - 1;
		// find right bracket
		char cBraR = name.charAt(end);
		if (cBraR != ')') { // no right bracket
			// return "filename(1).ext"
			fileName = parent + name + "(1)" + ext;
			return getNotExistsFile(new File(fileName));
		}
		// find left bracket
		int iBraL = full.lastIndexOf('(', end);
		if (iBraL == -1) { // no left bracket
			// return "filename(1).ext"
			fileName = parent + name + "(1)" + ext;
			return getNotExistsFile(new File(fileName));
		}
		// get string between left bracket and right bracket
		String s = full.substring(iBraL + 1, end);
		try {
			// parse "s" to int
			int i = Integer.parseInt(s);
			// return "filename(i+1).ext"
			fileName = parent + name.substring(0, iBraL) + "(" + (++i) + ")" + ext;
			return getNotExistsFile(new File(fileName));
		} catch (NumberFormatException ex) {
			// if "s" does not contain a parsable integer
			// return "filename(1).ext"
			fileName = parent + name + "(1)" + ext;
			return getNotExistsFile(new File(fileName));
		}
	}

	public static String encodeFileName(String fileName, String agent, boolean isOsWindows) {
		String codedFileName = null;
		if (isOsWindows) {
			try {
				codedFileName = new String(fileName.getBytes(), "ISO-8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else {
			if (null != agent && -1 != agent.indexOf("MSIE")) {
				String prefix = fileName.lastIndexOf(".") != -1 ? fileName.substring(0, fileName.lastIndexOf("."))
						: fileName;
				String extension = fileName.lastIndexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".")) : "";
				String name = null;
				try {
					name = java.net.URLEncoder.encode(prefix, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				if (name.lastIndexOf("%0A") != -1) {
					name = name.substring(0, name.length() - 3);
				}
				int limit = 150 - extension.length();
				if (name.length() > limit) {
					try {
						name = java.net.URLEncoder.encode(prefix.substring(0, Math.min(prefix.length(), limit / 9)),
								"UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					if (name.lastIndexOf("%0A") != -1) {
						name = name.substring(0, name.length() - 3);
					}
				}

				codedFileName = name + extension;
			} else if ((null != agent && -1 != agent.indexOf("Commons-HttpClient"))) {
				String prefix = fileName.lastIndexOf(".") != -1 ? fileName.substring(0, fileName.lastIndexOf("."))
						: fileName;
				String extension = fileName.lastIndexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".")) : "";
				String name = null;
				try {
					name = java.net.URLEncoder.encode(prefix, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				if (name.lastIndexOf("%0A") != -1) {
					name = name.substring(0, name.length() - 3);
				}

				codedFileName = name + extension;
			} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
				try {
					codedFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			} else {
				codedFileName = fileName;
			}
		}
		return codedFileName;
	}

	public static String replaceMsgKey(String msg, Locale locale, int flags) {
		if (msg != null) {
			Pattern pMsgKey = Pattern.compile(Constants.MSG_KEY_REGEX, flags);
			Matcher m = pMsgKey.matcher(msg);
			if (m.matches()) {
				final String resourcesLocation = "resources/ApplicationResources";
				ResourceBundle resources = ResourceBundle.getBundle(resourcesLocation);
				if (locale != null) {
					resources = ResourceBundle.getBundle(resourcesLocation, locale);
				}

				String msgKey = m.group(2);
				msg = msg.replaceAll(m.group(1), resources.getString(msgKey));
			}
		}
		return msg;
	}

	public static String replaceMsgKey(String msg, Locale locale) {
		return replaceMsgKey(msg, locale, 0);
	}

	public static String replaceMsgKey(String msg) {
		return replaceMsgKey(msg, null);
	}

	public static void writeToJson(HttpServletResponse response, boolean success, String message) {
		response.setDateHeader("Expires", -1);
		response.setHeader("Cache-Control", "no-store, private, post-check=0, pre-check=0, max-age=0");
		response.setHeader("Pragma", "no-cache");
		response.setCharacterEncoding(Constants.DEFAULT_CHARSET);

		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.element("success", success);
			if (message != null) {
				jsonObject.element("msg", message);
			}
			jsonObject.write(response.getWriter());
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void writeToJson(HttpServletResponse response, boolean success) {
		writeToJson(response, success, null);
	}

	public static void main(String[] args) throws Exception {
		
	}
}
